package cn.edu.jsu.zjj.aspect;

import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.model.entity.User;
import cn.edu.jsu.zjj.model.enums.UserRoleEnum;
import cn.edu.jsu.zjj.service.UserService;
import cn.hutool.json.JSONUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;


/**
 * 权限校验 AOP
 *
 */
@Aspect
@Component
@SuppressWarnings("all")
public class AuthAspect {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable,BaseException {
        String[] mustRoles = authCheck.mustRoles();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 当前登录用户
        User loginUser = userService.getLoginUser();
        if (loginUser == null) {
            throw new BaseException(MessageConstant.NO_AUTH_ERROR);
        }
        List<String> roleList = loginUser.getRoles();
        // 必须管理员权限才通过
        if (mustRoles != null && mustRoles.length > 0) {
            for (String mustRole : mustRoles) {
                UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
                if (mustUserRoleEnum == null) {
                    continue;
                }
                for (String userRole : roleList) {
                    // 必须有管理员权限
                    if (Objects.equals(UserRoleEnum.getEnumByValue(userRole), mustUserRoleEnum)) {
                        if (mustRole.equals(userRole)) {
                            // 通过权限校验，放行
                            return joinPoint.proceed();
                        }
                    }
                }
            }
        }
        throw new BaseException(MessageConstant.NO_AUTH_ERROR);
    }
}

